<template>
  <div class="flv-live">
    <div v-if="showClose" class="close el-icon-error" @click="close"></div>
    <video ref="_player" :controls="true" muted class="flv-live-player" />
  </div>
</template>

<script>
  import flvjs from 'flv.js'
  import {getMonitorVideo} from '@/api/monitor'
  export default {
    props: {
      code: {
        type: String,
        default: 'GKXTD001'
      },
      showClose: {
        type: Boolean,
        default: false
      },
    params: {
        type: [Object, null],
        default: null
      }
    },
    data() {
      return {
        leaveTime: 0,
        leaveTimeEnd: 1000 * 5, // 离开5秒停止播放
        leaveTimeout: null,
        player: null,
        video: {
          id: `flv_${+new Date()}${Math.ceil(Math.random() * 10000)}`,
          name: '',
          url: '',
          type: ''
        },
      }
    },
    watch: {
      code: {
        handler(n) {
          this.destroy()
          n && this.getUrl(n)
        },
        immediate: true
      }
    },
    created() {
      this.leaveTime && document.addEventListener('visibilitychange', this.windowTabChange)
    },
    beforeDestroy() {
      this.player && this.destroy()
      this.leaveTime && document.removeEventListener('visibilitychange', this.windowTabChange)
    },

    methods: {
      windowTabChange() {
        // 停止播放
        if (document.hidden) {
          this.leaveTime = +new Date()
          this.leaveTimeout = setTimeout(() => {
            this.destroy()
          }, this.leaveTimeEnd)
          return
        }
        // 恢复播放
        this.leaveTimeout && clearTimeout(this.leaveTimeout)
        const nowTime = +new Date()
        if (nowTime - this.leaveTime > this.leaveTimeEnd) {
          this.code && this.getUrl(this.code)
        }
      },

      async getUrl(code) {
        try {
            const params = this.params ? {code, type: 'flv', ...this.params}: {code, type: 'flv'}
          const { data } = await getMonitorVideo(params);
          this.video.url = data && data.src ? data.src : ''
          this.video.name = data && data.name ? data.name : ''
          this.video.type = data && data.type ? data.type : ''

          // 添加
          this.$emit('getName', this.video.name)
        } catch (error) {
          console.log('获取播放地址异常...', error)
          // setTimeout(() => { this.getUrl(code) }, 3000) // 3秒后重试
          return
        }
        if (flvjs.isSupported()) {
          this.player = new flvjs.FlvPlayer({
            type: 'flv',
            cors: true,
            isLive: true,
            // hasAudio: true,
            hasVideo: true,
            url: this.video.url
          }, {
            // enableWorker: true,
            // enableStashBuffer: false,
            // stashInitialSize: 128,
            // deferLoadAfterSourceOpen: false
          })
          this.player.attachMediaElement(this.$refs._player)
          this.player.load()
          this.player.play()
          this.player.on('error', this.onError)
          this.player.on('loading_complete', this.onloadingComplete)
          this.player.on('recovered_early_eof', this.onRecoveredEarlyEof)
          // this.player.on('media_info', this.onMediaInfo)
          // this.player.on('metadata_arrived', this.onMetadataArrived)
          // this.player.on('scriptdata_arrived', this.onScriptdataArrived)
          // this.player.on('statistics_info', this.onStatisticsInfo)

          // 监听窗口变化
          if (document.hidden !== undefined && !this.leaveTime) {
            this.leaveTime = +new Date()
            document.addEventListener('visibilitychange', this.windowTabChange)
          }
        }
      },
      onError(e) {
        console.log('##onError 视频流异常##', e)
        const nowTime = +new Date()
        if (document.hidden !== undefined || (document.hidden && nowTime - this.leaveTime < this.leaveTimeEnd)) {
          this.destroy()
          // this.code && this.getUrl(this.code)
        }
      },
      onloadingComplete(e) {
        console.log('##onloadingComplete 缓冲完成##', e)
      },
      onRecoveredEarlyEof(e) {
        console.log('##onRecoveredEarlyEof意外的网络波动，但自动恢复##', e)
      },
      // onMediaInfo(e) { console.log('##onMediaInfo##', e) },
      // onMetadataArrived(e) { console.log('##onMetadataArrived##', e) },
      // onScriptdataArrived(e) { console.log('##onScriptdataArrived##', e) },
      // onStatisticsInfo(e) { console.log('##onStatisticsInfo##', e) },


      close() {
        this.destroy()
        this.$emit('close', this.code)
      },

      // pause
      destroy() {
        try {
          if (this.player) {
            this.player.off('error', this.onError)
            this.player.off('loading_complete', this.onloadingComplete)
            this.player.off('recovered_early_eof', this.onRecoveredEarlyEof)
            this.player.pause()
            this.player.unload()
            this.player.detachMediaElement()
            this.player.destroy()
            this.player = null
          }
        } catch (error) {
          console.log(error)
        }
        this.leaveTimeout && clearTimeout()
        this.leaveTimeout = null
      }
    }
  }
</script>

<style lang="scss" scoped>
  .flv-live {
    width: 100%;
    height: 100%;
    position: relative;
    background: #000;
    .close {
        position: absolute;
        top: 0;
        right: 0;
        color: #fff;
        font-size: 30px;
        z-index: 999;
    }
    &-player {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
  }
</style>
